package com.huiyin.newpackage.ui.activity;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Adapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.huiyin.AppContext;
import com.huiyin.R;
import com.huiyin.adapter.ImageAdapter;
import com.huiyin.adapter.ReturnDetailGoodsAdapter;
import com.huiyin.bean.ImageData;
import com.huiyin.newpackage.base.NewBaseActivity;
import com.huiyin.newpackage.consts.HTTPConsts;
import com.huiyin.newpackage.entity.AppliedServiceInfoBean;
import com.huiyin.newpackage.entity.ApplyInfoBean;
import com.huiyin.newpackage.entity.BackGoodsStepInfo;
import com.huiyin.newpackage.entity.GoodsDetail;
import com.huiyin.newpackage.entity.LogisticsInfoDetail;
import com.huiyin.newpackage.entity.OrderInfo;
import com.huiyin.newpackage.entity.ServiceStepInfo;
import com.huiyin.newpackage.event.ApplyServiceDetailInfoEvent;
import com.huiyin.newpackage.event.CancelOrderServiceEvent;
import com.huiyin.newpackage.ui.adapter.BackGoodsProcessAdapter;
import com.huiyin.newpackage.ui.adapter.ProcessGoodsItemInnerAdapter;
import com.huiyin.newpackage.ui.widget.AlertDialog;
import com.huiyin.ui.user.order.BackGoodsActivity;
import com.huiyin.ui.user.order.BackGoodsForUpdateaInfoActivity;
import com.huiyin.utils.DeviceUtils;
import com.huiyin.wight.MyListView;

/**
 * 退货流程对应的Activity
 * 
 * @author 刘晨旭
 * 
 */
public class BackGoodsProcessActivity extends NewBaseActivity {

	private String returnId = "";

	/** 修改换货 **/
	public static final int REQUEST_CODE_UPDATE = 1;

	/** 退货Id **/
	public static final String EXTRA_RETURN_ID = "returnId";

	/** 商品列表 **/
	private MyListView product_listView;

	/** 售后类型 **/
	private TextView salTypeTv;

	/** 退款金额 **/
	private TextView returnMoneyTv;

	/** 申请理由 **/
	private TextView applyReasonTv;

	/** 描述问题 **/
	private TextView desQuestionTv;

	/** 上传凭证 **/
	private GridView uploadGridView;

	/** 上传凭证布局 **/
	private View uploadLayout;

	/** 修改申请 **/
	private Button upadteBtn;

	/** 取消申请 **/
	private Button cancelBtn;

	private TextView ab_back;

	/** 商品适配器 **/
	// private ReturnDetailGoodsAdapter adapter;
	ProcessGoodsItemInnerAdapter goodsDetailAdapter;

	/** 图片上传适配器 **/
	private ImageAdapter imageAdapter;

	private ApplyInfoBean applyInfoBean;

	private String orderServiceId = "";

	private AppliedServiceInfoBean details;

	private LinearLayout back_goods_info_layout;

	private LinearLayout back_goods_process_layout;// 进度查询

	private LinearLayout back_goods_trace_layout;// 物流跟踪

	private LinearLayout back_goods_time_address_layout;// 退货时间和退货

	private TextView return_goods;// 寄回商品按钮

	private TextView remain_time;// 退货剩余时间

	private TextView back_goods_address;// 退货地址

	private MyListView process_listView;// 进度ListView
	private BackGoodsProcessAdapter backGoodsProcessAdapter;// 进度adapter

	private TextView back_goods_company_name;// 物流公司

	private TextView back_goods_num;// 物流单号

	private MyListView goods_trace_listView;// 物流listview
	private BackGoodsProcessAdapter LogisticalProcessAdapter;// 物流进度adapter
	private TextView ab_title;
	private TextView uploaded_tv;
	private TextView service_no;
	
	private LinearLayout back_goods_time;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		register = true;
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_back_goods_process);
		Intent intent = getIntent();
		if (intent != null) {
			applyInfoBean = (ApplyInfoBean) intent.getSerializableExtra("ApplyInfo");
			orderServiceId = applyInfoBean.getORDER_SERVICE_ID() + "";
			if (TextUtils.isEmpty(orderServiceId)) {
				this.finish();
			} else {
				initView();
			}
		} else {
			this.finish();
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (!TextUtils.isEmpty(orderServiceId)) {
			ApplyServiceDetailInfoEvent.GetApplyServiceDetailInfo(client, orderServiceId);
		}
	}

	/**
	 * 初始化控件
	 */
	private void initView() {
		back_goods_time=(LinearLayout)findViewById(R.id.back_goods_time);
		service_no=(TextView)findViewById(R.id.service_no);
		uploaded_tv=(TextView)findViewById(R.id.uploaded_tv);
		back_goods_company_name = (TextView) findViewById(R.id.back_goods_company_name);
		back_goods_num = (TextView) findViewById(R.id.back_goods_num);
		product_listView = (MyListView) findViewById(R.id.product_listView);
		back_goods_info_layout = (LinearLayout) findViewById(R.id.back_goods_info_layout);
		back_goods_process_layout = (LinearLayout) findViewById(R.id.back_goods_process_layout);
		back_goods_trace_layout = (LinearLayout) findViewById(R.id.back_goods_trace_layout);
		back_goods_time_address_layout = (LinearLayout) findViewById(R.id.back_goods_time_address_layout);
		remain_time = (TextView) findViewById(R.id.remain_time);
		back_goods_address = (TextView) findViewById(R.id.back_goods_address);
		return_goods = (TextView) findViewById(R.id.return_goods);
		salTypeTv = (TextView) findViewById(R.id.sale_type);
		returnMoneyTv = (TextView) findViewById(R.id.return_money);
		applyReasonTv = (TextView) findViewById(R.id.apply_reason);
		desQuestionTv = (TextView) findViewById(R.id.des_question);
		uploadGridView = (GridView) findViewById(R.id.upload_gridview);
		uploadLayout = findViewById(R.id.upload_img_layout);
		upadteBtn = (Button) findViewById(R.id.update_apply_btn);
		cancelBtn = (Button) findViewById(R.id.cancel_apply_btn);
		ab_back = (TextView) findViewById(R.id.ab_back);
		ab_title=(TextView) findViewById(R.id.ab_title);
		ab_title.setText("");
		// //设置适配器
		goodsDetailAdapter = new ProcessGoodsItemInnerAdapter(null, this);
		product_listView.setAdapter(goodsDetailAdapter);
		int width = (DeviceUtils.getWidthMaxPx(this) * 4) / 5;
		imageAdapter = new ImageAdapter(this, width, 4);
		uploadGridView.setAdapter(imageAdapter);
		ab_back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				BackGoodsProcessActivity.this.finish();
			}
		});
		process_listView = (MyListView) findViewById(R.id.process_listView);
		backGoodsProcessAdapter = new BackGoodsProcessAdapter(this);
		process_listView.setAdapter(backGoodsProcessAdapter);

		goods_trace_listView = (MyListView) findViewById(R.id.goods_trace_listView);
		LogisticalProcessAdapter = new BackGoodsProcessAdapter(this);
		goods_trace_listView.setAdapter(LogisticalProcessAdapter);
		// uploadGridView.setOnItemClickListener(this);
		// //监听描述问题文本变换
		// upadteBtn.setOnClickListener(this);
		// cancelBtn.setOnClickListener(this);
	}

	/**
	 * 根据状态决定哪些控件显示
	 * 
	 * @param status
	 */
	private void showViews(int status) {
		product_listView.setVisibility(View.VISIBLE);
		back_goods_info_layout.setVisibility(View.VISIBLE);
		back_goods_process_layout.setVisibility(View.VISIBLE);
//		status = 1;
		// 审核中
		if (status == 1) {
//			ab_title.setText("服务单详情");
			ab_title.setText("审核中");
			upadteBtn.setVisibility(View.VISIBLE);
			cancelBtn.setVisibility(View.VISIBLE);
			upadteBtn.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					OrderInfo info=AppliedServiceInfoBean2OrderInfo(details);
					Intent intent = new Intent(BackGoodsProcessActivity.this, BackGoodsForUpdateaInfoActivity.class);
					intent.putExtra(BackGoodsActivity.EXTRA_ORDERID,info.getID()+"" );
					//整单
					if(details.getOrderServiceInfo().getIS_COMPLETE()==1){
						intent.putExtra("ID", "");
						intent.putExtra("order_service_detail_id", "");
//						intent.putExtra("order_service_detail_id", info.getorder+"");
					}
					//非整单
					else{
						intent.putExtra("ID", info.getOrderDetalList().get(0).getGOODS_ID()+"");
						intent.putExtra("order_service_detail_id", details.getOrderDetailList().get(0).getORDER_SERVICE_DETAIL_ID()+"");
					}
					intent.putExtra("order_service_id",details.getOrderServiceInfo().getORDER_SERVICE_ID()+"" );
					intent.putExtra("UpdateReturnOrder", true);
					intent.putExtra("Order", info);
					BackGoodsProcessActivity.this.startActivity(intent);
				}
			});
			cancelBtn.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					new AlertDialog(BackGoodsProcessActivity.this).builder().setMsg("确定取消申请？")
							.setPositiveButton("确定", new OnClickListener() {
								@Override
								public void onClick(View v) {
									CancelOrderServiceEvent.CancelOrderServiceEvent(client, orderServiceId);
								}
							}).setNegativeButton("取消", new OnClickListener() {
								@Override
								public void onClick(View v) {
								}
							}).show();
				}
			});
		}
		// 审核已通过等待买家寄回
		else if (status == 2) {
//			ab_title.setText("服务单详情");
			ab_title.setText("请退货");
			upadteBtn.setVisibility(View.GONE);
			cancelBtn.setVisibility(View.GONE);
			back_goods_time_address_layout.setVisibility(View.VISIBLE);
			if(TextUtils.isEmpty(details.getOrderServiceInfo().getREMAINING_TIME())){
				back_goods_time.setVisibility(View.GONE);				
			}
			else{
				back_goods_time.setVisibility(View.VISIBLE);	
				remain_time.setText(details.getOrderServiceInfo().getREMAINING_TIME());
			}
			back_goods_address.setText(details.getAddress().getPROVINCENAME() + details.getAddress().getCITYNAME()
					+ details.getAddress().getADDRESS());
			return_goods.setVisibility(View.VISIBLE);
			// 点击寄回商品按钮 跳转到寄回商品Activity
			return_goods.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent intent=new Intent(BackGoodsProcessActivity.this,SubmitExpressInfoActivity.class);
					intent.putExtra("order_service_id", details.getOrderServiceInfo().getORDER_SERVICE_ID()+"");
					intent.putExtra("user_name", details.getOrderServiceInfo().getUSER_NAME());
					intent.putExtra("store_id", details.getOrderServiceInfo().getSTORE_ID()+"");
					intent.putExtra("address", details.getAddress().getPROVINCENAME()
							+ details.getAddress().getCITYNAME()
							+ details.getAddress().getAREANAME()
							+ details.getAddress().getADDRESS());
					BackGoodsProcessActivity.this.startActivity(intent);
				}
			});
		}
		// status =3 status =4 status =5 status =6 status =7 status =8
		else {
			upadteBtn.setVisibility(View.GONE);
			cancelBtn.setVisibility(View.GONE);
			ab_title.setText(details.getOrderServiceInfo().getAPPLY_STATE_NAME());
			back_goods_trace_layout.setVisibility(View.VISIBLE);
			back_goods_company_name.setText(details.getOrderServiceLogistical().getEXPRESS_COMPANY());
			back_goods_num.setText(details.getOrderServiceLogistical().getEXPRESS_CODE());
			ArrayList<LogisticsInfoDetail> LogisticsInfos = new ArrayList<LogisticsInfoDetail>();
			if(details.getOrderServiceLogistical().getDATA()!=null){
				LogisticsInfos.addAll(details.getOrderServiceLogistical().getDATA());
			}
			ArrayList<BackGoodsStepInfo> logisticalInfos = new ArrayList<BackGoodsStepInfo>();
			for (LogisticsInfoDetail detail : LogisticsInfos) {
				BackGoodsStepInfo info = new BackGoodsStepInfo(detail.getFtime(), detail.getContext());
				logisticalInfos.add(info);
			}
			LogisticalProcessAdapter.setDatas(logisticalInfos);
		}
		goodsDetailAdapter.refreshDatas(details.getOrderDetailList());
		if(!TextUtils.isEmpty(details.getOrderServiceInfo().getSERVICE_CODE())){
			service_no.setText(details.getOrderServiceInfo().getSERVICE_CODE());
		}
		salTypeTv.setText(details.getOrderServiceInfo().getREFUNDS_MODE_NAME());// 售后类型
		DecimalFormat format=new DecimalFormat("#.00");
		returnMoneyTv.setText(format.format(details.getOrderServiceInfo().getREFUND_AMOUNT()) + "");// 实付金额
		applyReasonTv.setText(details.getOrderServiceInfo().getAPPLY_REASON());// 申请理由
		desQuestionTv.setText(details.getOrderServiceInfo().getAPPLY_REMARKS());// 问题描述
		String picsUrls = details.getOrderServiceInfo().getAPPLY_PICTURES();
		if(!TextUtils.isEmpty(picsUrls)){
			uploaded_tv.setText("上传凭证：");
			List<String> picsList = Arrays.asList(picsUrls.split(","));
			List<ImageData> imageDatas = new ArrayList<ImageData>();
			if (!(picsList == null || picsList.size() == 0)) {
				for (String string : picsList) {
					ImageData data = new ImageData(string, string);
					imageDatas.add(data);
				}
				imageAdapter.refreshData(imageDatas);
			}
		}
		else{
			uploaded_tv.setText("上传凭证：无");
		}
		ArrayList<ServiceStepInfo> orderServiceLog = details.getOrderServiceLog();
		ArrayList<BackGoodsStepInfo> stepInfos = new ArrayList<BackGoodsStepInfo>();
		for (ServiceStepInfo serviceStepInfo : orderServiceLog) {
			BackGoodsStepInfo info = new BackGoodsStepInfo(serviceStepInfo.getCREATE_TIME(),
					serviceStepInfo.getDESCRIPTION());
			stepInfos.add(info);
		}
		backGoodsProcessAdapter.setDatas(stepInfos);
	}

	public void onEvent(ApplyServiceDetailInfoEvent event) {
		finishProgress();
		if (event.type == HTTPConsts.HTTP_OK) {
			details = event.getRefundsInfo();
			showViews(details.getOrderServiceInfo().getAPPLY_STATE());
		} else {
			String message = event.msg;
			if (message != null) {
				showToast(message);
			}
		}
	}

	/**
	 * 取消申请
	 * 
	 * @param event
	 */
	public void onEvent(CancelOrderServiceEvent event) {
		if (event.type == HTTPConsts.HTTP_OK) {
			this.finish();
		} else {
			String message = event.msg;
			if (message != null) {
				showToast(message);
			}
		}
	}
	
	/**
	 * 
	 * @param info
	 * @return
	 */
	private OrderInfo AppliedServiceInfoBean2OrderInfo(AppliedServiceInfoBean info){
		OrderInfo order=new OrderInfo();
		order.setCREATE_DATE(info.getOrderServiceInfo().getCREATE_TIME());
		order.setID(info.getOrderServiceInfo().getORDER_ID());
		order.setORDER_CODE(info.getOrderServiceInfo().getORDER_CODE());
		order.setSTATUS(info.getOrderServiceInfo().getAPPLY_STATE());
		order.setSTATUS_NAME(info.getOrderServiceInfo().getAPPLY_STATE_NAME());
		order.setSTORE_ID(info.getOrderServiceInfo().getSTORE_ID());
		order.setSTORE_LOGO(info.getOrderServiceInfo().getSTORE_LOGO());
		order.setSTORE_NAME(info.getOrderServiceInfo().getSTATUS_NAME());
		order.setTOTAL_PRICE(info.getOrderServiceInfo().getREFUND_AMOUNT());
		order.setUSER_ID(AppContext.userId);
		order.setUSER_NAME(info.getOrderServiceInfo().getUSER_NAME());
		order.setUSER_PHONE(info.getOrderServiceInfo().getUSER_PHONE());
		order.setAPPLY_REASON(info.getOrderServiceInfo().getAPPLY_REASON());
		order.setAPPLY_REMARK(info.getOrderServiceInfo().getAPPLY_REMARKS());
		order.setAPPLY_IMGS(info.getOrderServiceInfo().getAPPLY_PICTURES());
		ArrayList<GoodsDetail>details=new ArrayList<GoodsDetail>();
		details.addAll(info.getOrderDetailList());
//		for (GoodsDetail goodsDetail : details) {
//			goodsDetail.setQUANTITY(goodsDetail.getGOODS_QUANTITY());
//		}
		order.setOrderDetalList(details);
		return order;
	}

}
